package com.akuhome.resource.aspect;

import com.akuhome.resource.enums.ResultEnum;
import com.akuhome.resource.exception.ResourceException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import java.util.Objects;

@Aspect
@Component
public class ValidAspect {
    @Pointcut("execution(* com.akuhome.resource.controller.*Controller.*(*,org.springframework.validation.BindingResult))")
    public void ValidPointcut(){
    }

    @Before("ValidPointcut()")
    public void before(JoinPoint joinPoint){
        Object[] os = joinPoint.getArgs();
        BindingResult bindingResult = (BindingResult) os[1];
        if (bindingResult.hasErrors()){
            throw new ResourceException(ResultEnum.FORM_IDENTIFY_ERROR, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
    }
}
